package com.example.fw;

import java.text.MessageFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactObject;

public class ContactHelper extends HelperWithDriverBase {

	public ContactHelper (ApplicationManager manager) {
		super(manager);
	}
	
	public Set<ContactObject> getContacts() {
		manager.getNavigationHelper().goToABHomepage();
		if ((findElements(By.tagName("form")).size() >= 2)) {
			driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
		}
		WebElement form = findElements(By.tagName("form")).get(2);
		
		 //private void buildContactCache() {
		 //       HashSet<ContactObject> set = new HashSet<ContactObject>();
		 //       List<WebElement> rows = getContactRows();
		 //       for (WebElement row : rows) {
		 //           ContactObject contact = new ContactObject()
		 //               .setFirstName(getFirstNameInRow(row))
		 //               .setLastName(getLastNameInRow(row))
		 //               .setId(row.findElement(By.tagName("input")).getAttribute("id"));
		 //           set.add(contact);
		 //       }
		 //       contactCache = new Contacts(set);
		 //   }
		
		
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		
		Set<ContactObject> contacts = new HashSet<ContactObject>();

		for (WebElement checkbox : checkboxes) {
			
			String name = checkbox.getAttribute("title");
			//get contacts name and lastname directly from table on the mainpage
			name = name.substring("Select (".length(), name.length()-")".length());
			String id = checkbox.getAttribute("value");
			
			ContactObject contact = new ContactObject()
			.setId(id)
			.setFullName(name);
			contacts.add(contact);
		}
		return contacts;
	}
	
	public void createContact(ContactObject contactObject) {
		manager.getNavigationHelper().goToABHomepage();
		initNewContactCreation();
		fillContactForm(contactObject, true);
		submitContactForm();
		manager.getNavigationHelper().goToABHomepage();
	}

	private void fillContactForm(ContactObject contactObject, boolean fillGroup) {
		type(By.name("firstname"), contactObject.firstName);
		type(By.name("lastname"), contactObject.lastName);
		type(By.name("address"), contactObject.mainAddress);
		type(By.name("home"), contactObject.homeTel);
		type(By.name("mobile"), contactObject.mobileTel);
		type(By.name("work"), contactObject.workTel);
		type(By.name("email"), contactObject.mainMail);
		type(By.name("email2"), contactObject.otherMail);
		type(By.name("byear"), contactObject.birthYear);
		type(By.name("address2"), contactObject.otherAddress);
		type(By.name("phone2"), contactObject.otherPhone);
		if (fillGroup) {
			select(By.name("new_group"), contactObject.newGroup);
		} else {
			if (driver.findElements(By.name("new_group")).size() > 0) {
				throw new Error ("There should be no group selector on the page!");
			}
		}
		select(By.name("bday"), contactObject.birthDay);
		select(By.name("bmonth"), contactObject.birthMonth);
	}
	
	private void initContactModification(int i) {
		String xpath = MessageFormat.format("(//img[@alt=''Edit''])[{0}]", i);
        click(By.xpath(xpath));
	}
	
	public void modifyContact(int i, ContactObject validContact) {
		manager.getNavigationHelper().goToABHomepage();
		initContactModification(i);
		fillContactForm(validContact, false);
		updateContactForm();
		manager.getNavigationHelper().goToABHomepage();
	}

	public void removeContact(int i) {
		manager.getNavigationHelper().goToABHomepage();
		initContactModification(i);
		deleteContact(2);
		manager.getNavigationHelper().goToABHomepage();
	}

	private void deleteContact(int i) {
		String xpath = MessageFormat.format("(//input[@name=''update''])[{0}]", i);
		if ((isElementPresent(By.xpath(xpath)) != true)) {
		driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);	
		}
		click(By.xpath(xpath));
	}

	private void submitContactForm() {
		//submit form
		click(By.name("submit"));
	}

	private void updateContactForm() {
		//submit form
		click(By.name("update"));
	}
	
	private void initNewContactCreation() {
		if ((isElementPresent(By.id("maintable")) != true))
			driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	 	click(By.linkText("add new"));
	}
}

